<?php

namespace iBrand\Shop\Core\Models;

use iBrand\Store\Backend\Model\Goods;
use iBrand\Component\Goods\Models\GoodsProduct;
use Illuminate\Database\Eloquent\Model;

class O2oGoodsProducts extends Model
{
	protected $guarded = ['id'];

	public function __construct(array $attributes = [])
	{
		parent::__construct($attributes);

		$prefix = config('ibrand.app.database.prefix', 'ibrand_');

		$this->setTable($prefix . 'o2o_goods_product');
	}

	public function O2oGoods()
	{
		return $this->belongsTo(O2oGoods::class, 'o2o_goods_id');
	}

	public function baseGoods()
	{
		return $this->belongsTo(Goods::class, 'goods_id')->withDefault();
	}

	public function baseProduct()
	{
		return $this->belongsTo(GoodsProduct::class, 'product_id')->withDefault();
	}

	/**
	 * 检测门店sku的库存
	 *
	 * @param $quantity
	 * @param $shop_id
	 *
	 * @return bool
	 */
	public function getIsInSale($quantity)
	{
		if ($o2oGoods = $this->o2oGoods) {
			return $o2oGoods && $o2oGoods->status == 1 && $this->store_nums >= $quantity;
		}

		return false;
	}

	public function getStockQty()
	{
		return $this->store_nums;
	}

	public function restoreStock($quantity)
	{
		$this->store_nums = $this->store_nums + $quantity;

		$this->O2oGoods->restoreStock($quantity);
	}

	public function reduceStock($quantity)
	{
		$this->store_nums = $this->store_nums - $quantity;

		$this->O2oGoods->reduceStock($quantity);
	}

	public function increaseSales($quantity)
	{
		$this->O2oGoods->sale = $this->O2oGoods->sale + $quantity;
		$this->O2oGoods->save();
	}

	public function restoreSales($quantity)
	{
		$this->O2oGoods->sale = $this->O2oGoods->sale - $quantity;
		$this->O2oGoods->save();
	}
}